package com.sugon.controller.device;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.AutoLog;
import com.sugon.annotation.LimitSubmit;
import com.sugon.dao.DevMaintenancePlanPreviewDao;
import com.sugon.dao.DevTypeDao;
import com.sugon.entity.DevMainBaseEntity;
import com.sugon.entity.DevTypeEntity;
import com.sugon.service.DevMainBaseHistoryService;
import com.sugon.service.DevMainBaseService;
import com.sugon.service.SysConfigService;
import com.sugon.utils.PageUtils;
import com.sugon.utils.Query;
import com.sugon.utils.R;
import com.sugon.utils.RRException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 维护库Controller
 *
 * @author sugon
 * @date 2019-07-16 14:46:43
 */
@Controller
@RequestMapping("devmainbase")
public class DevMainBaseController {

    @Resource
    private SysConfigService configService;
    @Resource
    private DevMainBaseService devMainBaseService;
    @Resource
    private DevMainBaseHistoryService devMainBaseHistoryService;
    @Resource
    private DevMaintenancePlanPreviewDao devPmPlanPreviewDao;
    @Resource
    private DevTypeDao devTypeDao;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("devmainbase:list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {

        //查询列表数据
        Query query = new Query(params);

        List<DevMainBaseEntity> devMainBaseList = devMainBaseService.queryList(query);
        int total = devMainBaseService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(devMainBaseList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    @RequestMapping("/listAll")
    @ResponseBody
    public R listAll(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<DevMainBaseEntity> devMainBaseList = devMainBaseService.queryAllList(query);
        int total = devMainBaseService.queryAllTotal(query);

        PageUtils pageUtil = new PageUtils(devMainBaseList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
//    @RequiresPermissions("devmainbase:info")
    @ResponseBody
    public R info(@PathVariable("id") String id) {
        DevMainBaseEntity devMainBase = devMainBaseService.queryObject(id);

        return R.ok().put("devMainBase", devMainBase);
    }

    /**
     * 保存
     */
    @AutoLog("维护库内容新增")
    @RequestMapping("/save")
    @RequiresPermissions("devmainbase:save")
    @ResponseBody
    public R save(@RequestBody DevMainBaseEntity devMainBase) {
        // 实施频率必填
        if (devMainBase.getFreRate() == null) {
            return R.error("实施频率必填！");
        }
        // 设备分类必填
        if (StrUtil.isEmpty(devMainBase.getDevType())) {
            return R.error("设备分类必填！");
        }
        // 校验设备分类是否存在
        DevTypeEntity devType = devTypeDao.queryObjectByCode(devMainBase.getDevType());
        if (devType == null) {
            return R.error("设备分类必填！");
        }
        // 只能填设备小类
        if (!NumberUtil.equals(devType.getTypeTp(), 0)) {
            return R.error("设备分类只能指定设备小类！");
        }
        boolean saveFlag = devMainBaseService.save(devMainBase) > 0;
        if (saveFlag) {
            // 记录维护项变动履历
            devMainBaseHistoryService.recordHistory("NEW", devMainBase);
        }
        return saveFlag ? R.ok() : R.error();
    }

    /**
     * 修改
     */
    @AutoLog("维护库内容修改")
    @RequestMapping("/update")
    @RequiresPermissions("devmainbase:update")
    @ResponseBody
    public R update(@RequestBody DevMainBaseEntity devMainBase) {
        // 实施频率必填
        if (devMainBase.getFreRate() == null) {
            return R.error("实施频率必填！");
        }
        // 设备分类必填
        if (StrUtil.isEmpty(devMainBase.getDevType())) {
            return R.error("设备分类必填！");
        }
        // 校验设备分类是否存在
        DevTypeEntity devType = devTypeDao.queryObjectByCode(devMainBase.getDevType());
        if (devType == null) {
            return R.error("设备分类必填！");
        }
        // 只能填设备小类
        if (!NumberUtil.equals(devType.getTypeTp(), 0)) {
            return R.error("设备分类只能指定设备小类！");
        }
        boolean updateFlag = devMainBaseService.update(devMainBase) > 0;
        if (updateFlag) {
            // 记录维护项变动履历
            devMainBaseHistoryService.recordHistory("UPDATE", devMainBase);
        }
        return updateFlag ? R.ok() : R.error();
    }

    /**
     * 修改失效标识-启用
     */
    @AutoLog("更新失效标识")
    @RequestMapping("/switchOn")
    @RequiresPermissions("devmainbase:switchFlag")
    @ResponseBody
    public R switchOn(@RequestBody String[] ids) {
        if (ArrayUtil.isEmpty(ids)) {
            return R.error("请选中记录后再执行该操作！");
        }
        // 启用当前设备规程
        devMainBaseService.switchStatus(true, ids);
        for (String id : ids) {
            DevMainBaseEntity devMainBase = devMainBaseService.queryObject(id);
            if (devMainBase != null) {
                // 记录维护项变动履历
                devMainBaseHistoryService.recordHistory("ENABLE", devMainBase);
            }
        }
        return R.ok();
    }

    /**
     * 修改失效标识-禁用
     */
    @AutoLog("更新失效标识")
    @RequestMapping("/switchOff")
    @RequiresPermissions("devmainbase:switchFlag")
    @ResponseBody
    public R switchOff(@RequestBody String[] ids) {
        if (ArrayUtil.isEmpty(ids)) {
            return R.error("请选中记录后再执行该操作！");
        }
        devMainBaseService.switchStatus(false, ids);
        for (String id : ids) {
            DevMainBaseEntity devMainBase = devMainBaseService.queryObject(id);
            if (devMainBase != null) {
                // 记录维护项变动履历
                devMainBaseHistoryService.recordHistory("DISABLE", devMainBase);
            }
        }
        return R.ok();
    }

    /**
     * 删除设备维护项
     */
    @LimitSubmit(key = "deleteDevPmItem:%s")
    @RequestMapping("/delete")
    @RequiresPermissions("devmainbase:delete")
    @ResponseBody
    public R delete(@RequestBody String[] ids) {
        if (ArrayUtil.isEmpty(ids)) {
            return R.error("请选中记录后再执行该操作！");
        }
        for (String id : ids) {
            // 校验是否存在
            DevMainBaseEntity devMainBase = devMainBaseService.queryObject(id);
            if (devMainBase == null) {
                continue;
            }
            // 如果已关联维护计划，则不允许删除
            int count = devPmPlanPreviewDao.countDevMainItemId(id);
            if (count > 0) {
                return R.error("该维护项已参与制定维护工单，不允许删除！！");
            }
            // 记录维护项变动履历
            devMainBaseHistoryService.recordHistory("DELETE", devMainBase);
            // 删除
            devMainBaseService.delete(id);
        }
        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<DevMainBaseEntity> list = devMainBaseService.queryList(params);

        return R.ok().put("list", list);
    }

    /**
     * 查询设备的维护项
     *
     * @param params
     * @return
     */
    @RequestMapping("/listAllByDev")
    @ResponseBody
    public R listAllByDev(@RequestParam Map<String, Object> params) {

        //查询列表数据
        Query query = new Query(params);

        List<DevMainBaseEntity> devMainBaseList = devMainBaseService.queryAllByDevList(query);
        int total = devMainBaseService.queryAllByDevTotal(query);

        PageUtils pageUtil = new PageUtils(devMainBaseList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    @RequestMapping("/export")
    @ResponseBody
    @AutoLog("执行导出数据")
    public void export(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
        // 设置导出EXCEL模板名称
        modelMap.put(TemplateExcelConstants.FILE_NAME, "设备预防性维护项导出_" + DateUtil.format(DateUtil.date(), "yyyyMMdd"));
        // 设置导出模板参数
        TemplateExportParams templateExportParams = new TemplateExportParams(configService.getPoiTemplatePath() + "devMainBaseIOTemplate.xlsx");
        templateExportParams.setColForEach(true);
        modelMap.put(TemplateExcelConstants.PARAMS, templateExportParams);
        // 获取设备维护计划预览模板数据
        Map<String, Object> mapData = MapUtil.newHashMap(1);
        // 获取预防性维护计划数据
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("mainType", 2);
        mapData.put("devMainBaseList", devMainBaseService.queryAllList(queryParam));
        modelMap.put(TemplateExcelConstants.MAP_DATA, mapData);
        PoiBaseView.render(modelMap, request, response, TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);
    }

    /**
     * excel预防性导入
     */
    @RequestMapping("/importPM")
    @ResponseBody
    public R importPM(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        int count = devMainBaseService.importPM(file);

        return R.ok("成功导入" + count + "条数据");
    }

    /**
     * excel预测性导入
     */
    @RequestMapping("/importPDM")
    @ResponseBody
    public R importPDM(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        int count = devMainBaseService.importPDM(file);

        return R.ok("成功导入" + count + "条数据");
    }
}

